//
//  NRWAppVersionManager.m
//  NRWMall
//
//  Created by 张记 on 2018/6/22.
//  Copyright © 2018年 com.anpxd. All rights reserved.
//

#import "NRWAppVersionManager.h"
#import <UIKit/UIKit.h>
#import "NRWUpdataAppApi.h"
#import "NRWAppstoreApi.h"

@interface NRWAppVersionManager ()<YTKRequestDelegate>
@property (nonatomic, strong) NRWUpdataAppApi *updataApi;
@property (nonatomic, strong) NRWAppstoreApi *storeApi;
@end

@implementation NRWAppVersionManager
-(NRWUpdataAppApi *)updataApi{
    if (!_updataApi) {
        _updataApi = [[NRWUpdataAppApi alloc] init];
        _updataApi.delegate = self;
    }
    return _updataApi;
}
-(NRWAppstoreApi *)storeApi{
    if (!_storeApi) {
        _storeApi = [[NRWAppstoreApi alloc] init];
        _storeApi.delegate = self;
    }
    return _storeApi;
}
+ (instancetype)sharedInstance {
    static NRWAppVersionManager *sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
/**
 *  初始化信息配置
 */
- (void)configureApp{
    
    [self getWhiteVerdionList];
    
}

/**
 *  懒加载
 */
- (NRWAppInfoModel *)versionInfo{
    if (!_versionInfo) {
        _versionInfo = [NRWAppInfoModel new];
    }
    return _versionInfo;
}
/**
 *  向自己的后台请求白名单信息
 */
- (void)getWhiteVerdionList {
    [self.updataApi start];
////    if (needUpdate) {
//        [NRWAppVersionManager sharedInstance].needsForceUpdate = NO;
////    }
//
//    [[NRWAppVersionManager sharedInstance]checkAppVersionIsInitiative:NO];
    
}
- (void)requestFinished:(__kindof YTKBaseRequest *)request {
    if (request == self.updataApi) {
        if ([request.responseObject[@"result"][@"apkForce"] integerValue] == 1){
            [NRWAppVersionManager sharedInstance].needsForceUpdate = YES;
        }else{
            [NRWAppVersionManager sharedInstance].needsForceUpdate = NO;
        }
        [self.storeApi start];
        
//        [[NRWAppVersionManager sharedInstance]checkAppVersionIsInitiative:NO];
    }else if (request == self.storeApi){
        
        NSArray *infoArray = [request.responseObject objectForKey:@"results"];
        if (infoArray && infoArray.count > 0) {
            NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
            //描述
            self.versionInfo.releaseNote = releaseInfo[@"releaseNotes"];
            self.versionInfo.version = releaseInfo[@"version"];
            self.versionInfo.URI = releaseInfo[@"trackViewUrl"];
            
            if (self.needsForceUpdate) {
                //强制更新 发送通知   通知接受对象可以更加自己项目情况来定
                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAppShouldUpdate object:@{@"URI":self.versionInfo.URI}];
                return;
            }
            //是否忽略这个版本
            self.versionIgnored = ([self.versionInfo.version isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:UDkUpdateIgnoredVersion]]);
            //要判断这里忽略过的版本是不是更新了 和本地版本号已经一样了
            if ([VERSION isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:UDkUpdateIgnoredVersion]]) {
                self.versionIgnored = NO;
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:UDkUpdateIgnoredVersion];
            }
            self.hasNewVersion = ([VERSION compare:self.versionInfo.version options:NSNumericSearch] == NSOrderedAscending);
            
            if (self.versionIgnored) {
                NSLog(@"忽略的版本");
                return;
            }
            if (self.hasNewVersion) {
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"新版本%@",self.versionInfo.version] message:[NSString stringWithFormat:@"%@",self.versionInfo.releaseNote] preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel
                                                               handler:^(UIAlertAction * action) {
                                                                   
                                                                   
                                                               }];
                UIAlertAction* updata = [UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDestructive
                                                               handler:^(UIAlertAction * action) {
                                                                   NSURL *url = [NSURL URLWithString:self.versionInfo.URI];
                                                                   if ([[UIApplication sharedApplication]canOpenURL:url]) {
                                                                       [[UIApplication sharedApplication] openURL:url];
                                                                   }
                                                               }];
                UIAlertAction* ignore = [UIAlertAction actionWithTitle:@"忽略此版本" style:UIAlertActionStyleDestructive
                                                               handler:^(UIAlertAction * action) {
                                                                   [self ignoreCurrentVersion];
                                                               }];
                [alert addAction:updata];
                [alert addAction:ignore];
                [alert addAction:cancel];
                [[AppDelegate shareAppDelegate].getCurrentUIVC  presentViewController:alert animated:YES completion:nil];
                
            }
            
        }
        
    }
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request {
    
    
}
/**
 *  版本更新是否退出登录 或者清除数据库什么的 暂时用不到
 */
- (void)cheackAppVersion{
    
}




- (void)ignoreCurrentVersion {
    
    [[NSUserDefaults standardUserDefaults] setObject:self.versionInfo.version forKey:UDkUpdateIgnoredVersion];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
@end

@implementation NRWAppInfoModel

@end
